package codegenerator.generator;

import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import baytony.util.StringUtil;
import baytony.util.Util;
import baytony.util.log.Log;
import codegenerator.CodeGeneratorException;
import codegenerator.ColumnInfo;
import codegenerator.CommonHelper;
import codegenerator.FileBean;
import codegenerator.JspFileBean;
import codegenerator.TableInfo;

public class IndexGenerator extends JspGenerator {

private static final Logger logger = Log.getLogger();
	
	private static final String PROJECT_NAME = "#projectName#";
	private static final String CLASS_NAME = "#className#";
	private static final String BEAN_GETTER = "#beanGetter#";
	private static final String BEAN_COUNT = "#getterCounts#";
	private static final String COLUMN_NAME = "#columnName#";
	private static final String LINE = "<td>beanGetter</td>";
	private static final String TITLE_LINE = "<th>columnName</th>";
	/*private static final String LINE = "<li>beanGetter</li>";
	private static final String TITLE_LINE = "<li>columnName</li>";*/
	private static final String[] BG_COLOR = {"FEFFAF", "D6FFAF"};

	@SuppressWarnings("unchecked")
	@Override
	public FileBean createInfo(TableInfo table) throws CodeGeneratorException {
		logger.trace("*** create index.jsp, table name : " + table.getName());
		String jtmpContent = super.readJtmp("index.jtmp");
		String projectName = generatorHelper.getProjectName();
		String tableName = table.getName();
		jtmpContent = jtmpContent.replaceAll(PROJECT_NAME, projectName);
		jtmpContent = jtmpContent.replaceAll(CLASS_NAME, CommonHelper.table2ClassName(tableName));
		
		List<ColumnInfo> primaryKeys = table.getPrimaryKey();
		List<ColumnInfo> columns = table.getColumns();
		List<String> getterMethods = new ArrayList<String>();
//		List<String> getters = this.column2Getter(primaryKeys, columns);
		getterMethods.addAll(this.createPrimaryKeyGet(primaryKeys));
		getterMethods.addAll(this.column2Getter(columns));
		jtmpContent = jtmpContent.replaceAll(BEAN_GETTER, this.getterStr(getterMethods));
		
		int columnCount = this.columnCount(primaryKeys, columns);
		jtmpContent = jtmpContent.replaceAll(BEAN_COUNT, String.valueOf(columnCount));
		
		jtmpContent = jtmpContent.replaceAll(COLUMN_NAME, this.createColumnTitle(primaryKeys, columns));
		
		FileBean result = new JspFileBean();
		result.setFileName(this.fileName(table));
		result.setContent(jtmpContent);
		result.setPath(generatorHelper.getPageOutputPath());
		return result;
	}
	
	/**
	 * 產生欄位的title
	 *
	 * @param lists
	 * @return
	 */
	private String createColumnTitle(List<ColumnInfo>...lists) {
		StringBuffer sb = new StringBuffer();
		for(List<ColumnInfo> list : lists) {
			for(ColumnInfo column : list) {
				String title = StringUtil.isEmptyString(column.getRemark())?column.getName():column.getRemark();
				sb.append(this.createColumnTitle(title));
				sb.append("\n");
			}
		}
		return sb.toString();
	}
	
	/**
	 * 產生欄位的title
	 *
	 * @param title
	 * @return
	 */
	private String createColumnTitle(String title) {
		String titleLine = TITLE_LINE;
		return titleLine.replaceAll("columnName", title);
	}
	
	/**
	 * 產稱 primary key 的 getter
	 *
	 * @param columns
	 * @return
	 * @throws CodeGeneratorException
	 */
	private List<String> createPrimaryKeyGet(List<ColumnInfo> columns) throws CodeGeneratorException {
		if(Util.isEmptyList(columns)) 
			throw new CodeGeneratorException("*** no primary keys error ***");
		List<String> result = new ArrayList<String>();		
		if(columns.size() == 1) {
			String columnName = columns.get(0).getName();
			result.add(this.createGetter(columnName));
		}
		else {
			StringBuffer sb = new StringBuffer();
			for(ColumnInfo column : columns) {
				String line = LINE;
				String columnName = column.getName();
				sb.append("<%=bean.getPk().get");
				sb.append(CommonHelper.column2MethodName(columnName));
				sb.append("() %>");				
				line = line.replaceAll("beanGetter", sb.toString());
				result.add(line + "\n\t");
				sb.delete(0, sb.length());
			}
		}
		return result;
	}
	
	/**
	 * 產生.jsp在WEB-INF/jsp/下的資料夾名稱以及檔案名稱
	 *
	 * @param table
	 * @return
	 */
	private String fileName(TableInfo table) {
		return super.fileName(table, "index");
	}
	
	/**
	 * 計算欄位數
	 *
	 * @param columnList
	 * @return
	 */
	private int columnCount(List<ColumnInfo>...columnList) {
		int result = 0;
		for(List<ColumnInfo> columns : columnList) {
			result += columns.size();
		}
		return result;
	}
	
	/**
	 * 產生getter字串
	 *
	 * @param methodNames
	 * @return
	 */
	private String getterStr(List<String> methodNames) {
		StringBuffer sb = new StringBuffer();
		for(String methodName : methodNames) {
			sb.append(methodName);
		}
		return sb.toString();
	}	
	
	/**
	 * 產生getter字串
	 *
	 * @param columns
	 * @return
	 */
	private List<String> column2Getter(List<ColumnInfo> columns) {
		List<String> result = new ArrayList<String>();
		for(ColumnInfo column : columns) {
			result.add(this.createGetter(column.getName()) + "\n\t");
		}
		return result;
	}
	
	/**
	 * 產生<%=bean.getXXX() %>字串
	 *
	 * @param columnName
	 * @return
	 */
	private String createGetter(String columnName) {
		logger.trace("*** create getter, column name : " + columnName);
		String temp = LINE;
		String fullName = "<%=bean.get" + CommonHelper.column2MethodName(columnName) + "() %>";
		String result = temp.replaceAll("beanGetter", fullName);
		logger.trace("*** create result : " + result);
		return result;
	}

}
